package com.csx.governance.sample.providerB.controller;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author cuisongxu
 * @date 2023/4/2 18:34
 */
@RequestMapping("/providerB")
@RestController
public class ProviderBController {

    public static final String TRAFFIC_TOPIC = "traffic_topic";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private Registration registration;

    @Autowired
    public RocketMQTemplate rocketMQTemplate;

    @GetMapping("/test")
    public String test() {
        Map<String, String> metadata = registration.getMetadata();
        String host = registration.getHost();
        int port = registration.getPort();
        String instanceInfo = host + ":" + port + "  metadata: " + metadata.toString();
        String url = "http://consumerC/consumerC/test";
        String res = restTemplate.getForObject(url, String.class);
        return "providerB " + instanceInfo + " ->  \n" + res;
    }

    /**
     * 这个是提供方,与test接口逻辑相同
     * @return
     */
    @GetMapping("/testFeign")
    public String testFeign() {
        Map<String, String> metadata = registration.getMetadata();
        String host = registration.getHost();
        int port = registration.getPort();
        String instanceInfo = host + ":" + port + "  metadata: " + metadata.toString();
        String url = "http://consumerC:8003/consumerC/testFeign";
        String res = restTemplate.getForObject(url, String.class);
        return "providerB openfeign " + instanceInfo + " ->  \n" + res;
    }

    @GetMapping("/sendMsg")
    public String sendMsg(@RequestParam("msg") String msg) {
        rocketMQTemplate.convertAndSend(TRAFFIC_TOPIC, "producer send msg: " + msg);
        Map<String, String> metadata = registration.getMetadata();
        String host = registration.getHost();
        int port = registration.getPort();
        String instanceInfo = host + ":" + port + "  metadata: " + metadata.toString();
        return "providerB " + instanceInfo + " ->  \n";
    }
}
